package com.example.lottery_system.dao.handler;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.example.lottery_system.dao.dataobject.Encrypt;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Slf4j
@MappedTypes(Encrypt.class) //需要转换或者转换为的Java类型
@MappedJdbcTypes(JdbcType.VARCHAR) //MySQL数据类型
public class EncryptTypeHandler extends BaseTypeHandler<Encrypt> {
    private final byte[] key = "manwhatcanisayhh".getBytes();
    /**
     * 设置参数
     * @param preparedStatement SQL预编译对象
     * @param i 需要赋值的索引位置
     * @param encrypt 原本位置i需要赋的值
     * @param jdbcType jdbc类型
     * @throws SQLException
     */
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Encrypt encrypt, JdbcType jdbcType) throws SQLException {
        if (encrypt == null || encrypt.getValue() == null) {
            preparedStatement.setString(i, null);
            return;
        }
        System.out.println("需要加密的内容:" + encrypt.getValue());
        AES aes = SecureUtil.aes(key);
        preparedStatement.setString(i,aes.encryptHex(encrypt.getValue()));
    }

    @Override
    public Encrypt getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return decrypt(resultSet.getString(s));
    }

    @Override
    public Encrypt getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return decrypt(resultSet.getString(i));
    }

    private Encrypt decrypt(String string) {
        if (!StringUtils.hasText(string)) return null;
        return new Encrypt(SecureUtil.aes(key).decryptStr(string));
    }

    @Override
    public Encrypt getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return decrypt(callableStatement.getString(i));
    }
}
